<template>
  <BoTable
    :columns="columns"
    :request="_projectQuickReportList"
    :row-selection="rowSelection"
    row-key="id"
    ref="tableRef"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onConfig"> 地震触发配置 </Button>
        <Button :disabled="!selectKeys?.length" @click="onDelete">删除</Button>
      </Space>
    </template>
    <template #info="{ record }">
      <div class="eewMessage">
        <div>
          <div>事件：</div>
          <div>{{ record.earthquakeQuickReportPO?.eewId || '--' }}</div>
        </div>
        <div>
          <div>震级：</div>
          <div>{{ record.earthquakeQuickReportPO?.magnitude || '--' }}级</div>
        </div>
        <div>
          <div>深度：</div>
          <div>{{ record.earthquakeQuickReportPO?.focdepth || '--' }}km</div>
        </div>
        <div>
          <div>经度：</div>
          <div>{{ record.earthquakeQuickReportPO?.epiLon || '--' }}°</div>
        </div>
        <div>
          <div>纬度：</div>
          <div>{{ record.earthquakeQuickReportPO?.epiLat || '--' }}°</div>
        </div>
        <div>
          <div>地址：</div>
          <div>{{ record.earthquakeQuickReportPO?.locname || '--' }}</div>
        </div>
      </div>
    </template>
    <template #devices="{ record }">
      <div class="info" v-if="Array.isArray(record.projectVO.deviceList)">
        <div v-for="item in record.projectVO?.deviceList">
          {{ item.stationId || '--' }}
        </div>
      </div>
      <div v-else>--</div>
    </template>
  </BoTable>
  <FormModal :columns="item"> </FormModal>

  <Modal
    v-model:open="flag"
    @ok="handleOk"
    :footer="false"
    wrapClassName="view_modal"
    :destroyOnClose="true"
  >
    <triggerData
      :deviceInfo="deviceInfo"
      :title="showWitch === 'trigger' ? '设备触发数据' : '数据产出'"
      v-model:showWitch="showWitch"
      :fetchInfoApi="() => dataInfo"
      :data="dataInfo"
      :options="option"
    >
      <template #header v-if="showWitch == 'trigger'">
        <!-- <div class="custom_header">
          <div>
            <div>设备标识:</div>
            <div>{{ '--' }}</div>
          </div>
          <div>
            <div>采样率:</div>
            <div>{{ '--' }}</div>
          </div>
          <div>
            <div>仪器烈度:</div>
            <div>{{ '--' }}</div>
          </div>
        </div> -->
      </template>
    </triggerData>
  </Modal>
  <!-- 预览pdf -->
  <BoPreviewPdf
    title="预览"
    :iframe-url="iframeUrl"
    v-model:open="visible"
  ></BoPreviewPdf>

  <FormModal2 :columns="_item">
    <template #details>
      <div class="generate_error_msg">
        {{ generateErrorMsg || '-' }}
      </div>
    </template>
  </FormModal2>

  <FormModal3 :columns="_item">
    <template #details>
      <div class="intensity_data">
        <Row>
          <Col :span="16">
            <div class="map" :id="id"></div>
          </Col>
          <Col :span="8">
            <div class="right">
              <div class="title">仪器地震烈度分布图</div>
              <div class="right_item">
                <span>发震时刻：</span>
                <span>{{ intensityData.earthquakeStartTime || '-' }}</span>
              </div>
              <div class="right_item">
                <span>震中烈度：</span>
                <span>1</span>
              </div>
              <div class="right_item">
                <span>震源深度：</span>
                <span>{{ intensityData.focdepth || 0 }}km</span>
              </div>
              <div class="right_item">
                <span>地震震级：</span>
                <span>{{ intensityData.magnitude || 0 }}级</span>
              </div>
              <div class="right_item">
                <span>参考位置：</span>
                <span>{{ intensityData.locname || '-' }}</span>
              </div>
              <div class="right_list">设备震动情况</div>
              <div class="right_list_item label">
                <span>名称</span>
                <span>烈度</span>
              </div>
              <div class="list">
                <div
                  class="right_list_item"
                  v-for="(x, y) in stationInfo"
                  :key="y"
                >
                  <span>{{ y }}</span>
                  <span>{{ x }}</span>
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>
    </template>
  </FormModal3>
  <globalLoading v-model:visible="showLoading" tip="图表生成中..." />
</template>

<route lang="json">
{
  "name": "地震产出",
  "meta": { "title": "地震产出" }
}
</route>

<script setup lang="tsx">
import { computed, nextTick, onMounted, ref, useId, watch } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { createOlMap } from '@boeyo/hooks';
import { useDicts, useUserStore } from '@boeyo/portal';
import { download } from '@boeyo/shared';
import { BoFormProps, BoPreviewPdf, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Col, Modal, Row, Space, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { Overlay } from 'ol';
import { fromLonLat, toLonLat } from 'ol/proj';
import globalLoading from '@/components/globalLoading/index.vue';
import triggerData from '@/components/triggerData/index.vue';
import { getWaveInfo } from '@/utils/index';
import {
  createEarthquakeData,
  delProjectQuickReport,
  downloadGenerateById,
  fetchHistoryData,
  getInfo,
  intensity,
  projectQuickReportList,
  responseSpectrum,
  signal,
  update,
} from './api';

const userStore = useUserStore();
const license = userStore.license;
const stationInfo = ref({});
const intensityData = ref();
const { sysMagnitudeEnum } = useDicts(['sys_magnitude']);
let overlay;
const id = useId();
const { useOl, getMap } = createOlMap();
const { renderTile, renderFeature, animate } = useOl({
  target: id,
  tileUrl: 'http://ebs.dev.boeyo.com/map/pt/{z}/{x}/{y}/tile.png',
  maxZoom: 18,
  onClick(res) {
    console.log(res);
    message.info(`点击坐标 ${res.lonLat}`);
  },
});

const _projectQuickReportList = async (params: any) => {
  params.startTime =
    params.earthquakeArriveTime && params.earthquakeArriveTime.length
      ? dayjs(params.earthquakeArriveTime[0]).valueOf()
      : '';
  params.endTime =
    params.earthquakeArriveTime && params.earthquakeArriveTime.length
      ? dayjs(params.earthquakeArriveTime[1]).valueOf()
      : '';
  return await projectQuickReportList(params);
};
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  column: 1,
});
const { FormModal: FormModal3, open: open3 } = useFormModal({
  size: 'middle',
  column: 1,
});

const columns = computed<BoTableProps['columns']>(() => [
  {
    //这边传时间戳
    title: '发震时间',
    hideInTable: true,
    dataIndex: 'earthquakeArriveTime',
    valueType: 'dateRange',
    customRender({ record }) {
      return <span>{record.earthquakeArriveTime}</span>;
    },
  },
  {
    title: '震级',
    dataIndex: 'level',
    hideInTable: true,
    valueType: 'select',
    valueEnum: {
      ...sysMagnitudeEnum.value,
    },
  },
  {
    title: '震中地址',
    dataIndex: 'locname',
    hideInTable: true,
  },
  {
    title: '开始时间',
    dataIndex: 'earthquakeStartTime',
    hideInSearch: true,
  },
  {
    title: '到达时间',
    dataIndex: 'earthquakeArriveTime',
    hideInSearch: true,
  },
  {
    title: '结束时间',
    dataIndex: 'earthquakeEndTime',
    hideInSearch: true,
  },
  {
    title: '地震预警信息',
    dataIndex: 'info',
    hideInSearch: true,
  },
  {
    title: '震中距（km）',
    dataIndex: 'distance',
    hideInSearch: true,
  },
  {
    title: '关联设备',
    dataIndex: 'devices',
    hideInSearch: true,
  },
  {
    title: '产出数据',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '设备触发数据',
        onClick(record) {
          onDevices(record, 'trigger');
        },
      },
      {
        text: '数据产出',
        hidden: !['3', '4', '5'].some((item) =>
          (license.vipPaks as string[]).includes(item),
        ),
        onClick(record) {
          onDevices(record, 'signalNoiseRatio');
        },
      },
      {
        text: '烈度数据',
        hidden: !(license.vipPaks as string[])?.includes('6'),
        onClick: async (record) => {
          const {
            projectVO,
            earthquakeEndTime: endTime,
            earthquakeStartTime: startTime,
          } = record;
          const stationIds = [];
          projectVO.deviceList.forEach((i) => {
            if (!i.stationId) return;
            stationIds.push(i.stationId);
          });
          intensityData.value = {
            earthquakeStartTime: record.earthquakeStartTime,
            ...record.earthquakeQuickReportPO,
          };

          const res = await intensity({ stationIds, endTime, startTime });
          stationInfo.value = res.data;
          open3({
            title: '烈度数据',
            modalType: 'disabled',
            hideFooter: true,
            request: async (params: any) => {},
            defaultValue: record,
          });

          projectVO.deviceList.forEach((i, y) => {
            if (!i.stationId) return;
            nextTick(() => {
              const coordinate = [i.longitude, i.latitude];
              renderTile();
              animate({
                center: coordinate,
                duration: 100,
              });
              renderFeature({
                lonLat: coordinate,
                style: {
                  image: {
                    src: '/static/map/marker-icon.png',
                    scale: 0.5,
                  },
                },
              });
              const map = getMap();
              const box = document.createElement('div');
              box.className = 'custom_div';
              box.innerHTML = i.stationId;
              overlay = new Overlay({
                element: box,
                autoPan: {
                  animation: {
                    duration: 250,
                  },
                },
              });
              map.addOverlay(overlay);
              overlay.setPosition(fromLonLat(coordinate));
            });
          });
        },
      },
    ],
  },
  {
    title: '产出报告',
    dataIndex: 'operation1',
    hideInSearch: true,
    fixed: 'right',
    actions({ record }) {
      const style = {
        color: 'red',
      };
      return [
        {
          text: record.generateId ? (
            '预览'
          ) : (
            <span>
              <span style={style}>！</span>
              <span>预览</span>
            </span>
          ),
          onClick: async (record) => {
            if (!record.generateId) {
              generateErrorMsg.value = record.generateErrorMsg;
              return open2({
                title: '日志',
                modalType: 'disabled',
                hideFooter: true,
                request: async (params: any) => {},
                defaultValue: record,
              });
            }

            const result = await downloadGenerateById(record.generateId, 'pdf');
            const blob = new Blob([result.data], { type: 'application/pdf' });
            const imageUrl = URL.createObjectURL(blob);
            iframeUrl.value = imageUrl;
            visible.value = true;
          },
        },
        {
          text: '重新生成',
          hidden: canRegenerate.value,
          onClick: async (record) => {
            canRegenerate.value = true;
            message.loading('报告重新生成中..', 0);
            const res = await createEarthquakeData(record.id);
            message.destroy();
            if (res.code === 200) {
              message.success('报告生成完毕!');
            } else {
              message.info(res.msg);
            }
            canRegenerate.value = false;
            tableRef.value.refresh();
          },
        },
        {
          text: '下载',
          hidden: !record.generateId,
          onClick: async (record) => {
            const res = await downloadGenerateById(record.generateId, 'pdf');
            download(
              res.data as unknown as Blob,
              `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.pdf`,
            );
          },
        },
      ];
    },
  },
]);
const generateErrorMsg = ref('');
const logId = ref('');
const _item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'details',
    valueType: 'input',
    formItemProps: {
      wrapperCol: { span: 24 },
    },
  },
]);

const canRegenerate = ref(false);
const iframeUrl = ref();

const visible = ref(false);
const item = computed<BoFormProps['columns']>(() => [
  {
    title: '震中距',
    dataIndex: 'distance',
    valueType: 'inputNumber',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入震中距',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入震中距',
      max: 9999,
    },
  },
  {
    title: '震级',
    dataIndex: 'magnitude',
    valueType: 'inputNumber',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入震级',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入震级',
    },
  },
  {
    title: '是否启用',
    dataIndex: 'isEnable',
    valueType: 'radio',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择是否启用',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      options: [
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      placeholder: '请选择是否启用',
    },
  },
]);

const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const onConfig = async () => {
  const result = await getInfo();

  open({
    title: '地震触发配置',
    request: async (params: any) => {
      await update(params);
    },
    defaultValue: result.data,
  });
};
const handleOk = () => {};
const flag = ref(false);
const dataInfo = ref({});
const showWitch = ref();
const deviceInfo = ref([]);
const option: any = ref({});
const queryParams = ref({});
const queryParams2 = computed(() => {
  const start = queryParams.value.startTime;
  const startTime = start
    ? dayjs(start).subtract(15, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  const endTime = start
    ? dayjs(start).subtract(5, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  return { startTime, endTime, stationIds: deviceInfo.value };
});
const showLoading = ref(false);
const onDevices = async (record, type) => {
  // message.loading('图表生成中..', 0);
  showLoading.value = true;
  showWitch.value = type;
  const {
    projectVO,
    earthquakeEndTime: endTime,
    earthquakeStartTime: startTime,
  } = record;
  deviceInfo.value = projectVO.deviceList.map((i) => i.stationId);
  setTimeout(async () => {
    if (type === 'trigger') {
      try {
        const { dataInfo: data, deviceInfoList } = await getWaveInfo(
          deviceInfo.value,
          startTime,
          endTime,
          fetchHistoryData,
        );
        option.value.deviceInfoList = deviceInfoList;
        dataInfo.value = data;
      } catch (error) {
        showLoading.value = false;
      }
    } else {
      queryParams.value = {
        stationIds: deviceInfo.value,
        startTime,
        endTime,
      };
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
      init(signalData.data);
    }
    showLoading.value = false;
    flag.value = true;
  }, 300);
};

const tableRef = ref();
const onDelete = async () => {
  const ids = selectKeys.value.join(',');
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选中项数据？`,
    centered: true,
    onOk: async () => {
      await delProjectQuickReport(ids);
      selectKeys.value = [];
      tableRef.value.refresh();
      message.success('操作成功');
    },
  });
};
watch(
  () => showWitch.value,
  async (val) => {
    if (val === 'signalNoiseRatio') {
      if (!flag.value) return;
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
      init(signalData.data);
    } else if (val === 'waveform') {
      const signalData = await signal(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    } else if (val === 'spectrum') {
      const signalData = await responseSpectrum(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    }
  },
);

const init = (data) => {
  message.destroy();
  if (!Object.keys(data).length) {
    message.info('暂无数据!');
  }

  const resultList = Object.keys(data);
  option.value.deviceInfoList = deviceInfo.value.map((i) => {
    return {
      label: i,
      value: i,
      disabled: !resultList.includes(i.replaceAll('.', '')),
    };
  });
};
</script>

<style scoped lang="scss">
.eewMessage {
  > div {
    margin-bottom: 10px;
    display: flex;
    text-align: left;

    &:last-child {
      margin-bottom: 0;
    }
    div {
      flex: 1;
    }
  }
}

.info {
  display: flex;
  flex-direction: column;
  text-align: center;
  div {
    margin-bottom: 10px;
  }
}

.intensity_data {
  .map {
    height: 600px;
    margin-right: 10px;
  }
  .right {
    padding: 0 15px;
    .list {
      padding-right: 10px;
      max-height: 390px;
      overflow-y: auto;
    }
    .title {
      font-weight: 700;
      margin-bottom: 10px;
      font-size: 18px;
    }
    &_item {
      margin-bottom: 2px;
    }
    &_list {
      text-align: center;
      padding: 2px 0;
    }
    &_list_item {
      display: flex;
      border-bottom: 1px solid #fff;
      &.label {
        border: none;
        span {
          font-weight: 700;
        }
      }
      span {
        flex: 1;
        text-align: center;
      }
    }
  }
}
</style>

<style lang="scss">
.custom_div {
  background: #fff;
  color: #000;
  padding: 0 5px;
  transform: translateX(-50%) translateY(50%);
  border: 1px solid #000;
  border-radius: 2px;
}
</style>
